<?php

namespace EasyDB\Tools;

class Random
{
    /**
     * 生产随机数
     * @param int $length 长度
     * @param string $alphabet 元素集合
     * @return false|string
     */
    public static function character($length = 6, $alphabet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789')
    {
        mt_srand();
        if ($length >= strlen($alphabet)) {
            $rate     = intval($length / strlen($alphabet)) + 1;
            $alphabet = str_repeat($alphabet, $rate);
        }
        return substr(str_shuffle($alphabet), 0, $length);
    }


    /**
     * 生产指定长度的随机数字
     * @param int $length 长度
     * @return false|string
     */
    public static function number($length = 6)
    {
        return static::character($length, '0123456789');
    }


    /**
     * 数组中随机返回一个
     * @param array $data 数据
     * @return mixed|null
     */
    public static function arrayRandOne(array $data)
    {
        if (empty($data)) {
            return null;
        }
        mt_srand();
        return $data[array_rand($data)];
    }

    /**
     * 生产一个UUID4
     * 有概率重复|短时间内可以认为唯一
     * @return string
     */
    public static function makeUUIDV4()
    {
        mt_srand();
        $charId = strtolower(md5(uniqid(mt_rand(), true)));
        $hyphen = '-';
        return substr($charId, 0, 8) . $hyphen .
               substr($charId, 8, 4) . $hyphen .
               substr($charId, 12, 4) . $hyphen .
               substr($charId, 16, 4) . $hyphen .
               substr($charId, 20, 12);
    }

    /**
     * 生成随机字符串
     * @param int $length 长度
     * @return string
     */
    public static function createNonceStr(int $length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $str   = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}
